<template>
  <!-- 联想建议模块 -->
  <div class="SearchSuggestion">
    <van-cell v-for="(text, index) in suggestions" :key="index" icon="search" @click="$emit('search', text)">
      <div slot="title" v-html="highlight(text)"></div>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuggestionAPI } from '@/api/Search.js'
import { debounce } from 'lodash'
export default {
  name: 'SearchSuggestion',
  data() {
    return {
      suggestions:[] //联想建议数据列表
    }
  },
  props: {
    searchText: {
      type: String,
      require: true
    }
  },
  watch: {
    searchText: {
      // 防抖函数
      // 该回调将会在侦听开始之后被立即调用
      handler: debounce(function(val) {
        this.getSearchSuggestion(val)
      }, 500),
      // handler(val) {
      //   this.getSearchSuggestion(val)
      // },

      immediate: true
    }
  },
  methods: {
    // 获取联想建议的数据
    async getSearchSuggestion(q) {
      try {
        const { data } = await getSearchSuggestionAPI(q)
        this.suggestions = data.data.options
        // console.log(this.suggestions)
      } catch (err) {
        console.log(err)
      }
    },
    highlight(text) {
      const highlightStr = `<span class='active'>${this.searchText}</span>`
      const reg = new RegExp(this.searchText, 'gi')
      return text.replace(reg, highlightStr)
    }
  }
}
</script>

<style lang="less" scoped>
.SearchSuggestion{
  /deep/.active {
    color: #3296fa;
  }
}
</style>
